package com.learn.window.aggregation;


import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @create: 2023-04-23 17:19
 * @author: Mr.Du
 * --------------
 * @notes: 获取一段时间内（window size）每个用户（KeyBy）浏览的商品的最大价值的那条记录（ReduceFunction），
 * 并获得Key和WIndow信息
 **/
public class ReduceAndProcessFunction {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);
        DataStream<String> stream = env.socketTextStream("node1",9999);

        stream.process(new ProcessFunction<String, UserActionLog>() {
            @Override
            public void processElement(String value, ProcessFunction<String, UserActionLog>.Context context, Collector<UserActionLog> out) throws Exception {
              out.collect(JSON.parseObject(value, UserActionLog.class));
            }
        }).assignTimestampsAndWatermarks(WatermarkStrategy.<UserActionLog>forBoundedOutOfOrderness(Duration.ZERO)
                .withTimestampAssigner(new SerializableTimestampAssigner<UserActionLog>() {
                    @Override
                    public long extractTimestamp(UserActionLog element, long recordTimestamp) {
                        try {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            return format.parse(element.getEventTime()).getTime();
                        } catch (Exception e) {
                            e.printStackTrace();
                            return 0L;
                        }
                    }
                })).keyBy((KeySelector<UserActionLog, String>) UserActionLog::getUserID)
                // 构造TimeWindow
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                //窗口函数：获取这段窗口时间内每个用户浏览的商品的最大价值对应的那条记录
                .reduce(new ReduceFunction<UserActionLog>() {
                    @Override
                    public UserActionLog reduce(UserActionLog v1, UserActionLog v2) throws Exception {

                        return v1.getProductPrice() > v2.getProductPrice() ? v1 : v2;
                    }
                }, new ProcessWindowFunction<UserActionLog, String, String, TimeWindow>() {
                    @Override
                    public void process(String key, ProcessWindowFunction<UserActionLog, String, String, TimeWindow>.Context context, Iterable<UserActionLog> iterable, Collector<String> out) throws Exception {
                        UserActionLog max = iterable.iterator().next();
                        String windowStart = new DateTime(context.window().getStart(), DateTimeZone.forID("+08:00")).toString("yyyy-MM-dd HH:mm:ss");
                        String windowEnd = new DateTime(context.window().getEnd(), DateTimeZone.forID("+08:00")).toString("yyyy-MM-dd HH:mm:ss");
                        String record = "Key: " + key + " 窗口开始时间：" + windowStart + " 窗口结束时间：" + windowEnd + " 浏览的商品的最大价值对应的记录为：" + max;
                        out.collect(record);
                    }
                }).print();

        env.execute();
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class UserActionLog{
    private String userID;
    private String eventTime;
    private String eventType;
    private String productID;
    private Long productPrice;
}
